package api

import (
	"api-getaway/basic/config"
	"api-getaway/basic/model"
	"api-getaway/handler/request"
	"api-getaway/pkg"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

func SendSms(r *gin.Context) {
	var req request.SendSms
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    nil,
		})
		return
	}

	if !regexp.MustCompile(`^1[3-9]\d{9}$`).MatchString(req.Mobile) {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "手机号格式不正确",
			"data":    nil,
		})
		return
	}

	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+req.Mobile).Result()
	if result >= "1" {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "5分钟内最多发送3条验证码",
			"data":    nil,
		})
		return
	}

	code := rand.Intn(900000) + 100000
	codeKey := req.Mobile
	pkg.SendSms(strconv.Itoa(code), req.Mobile)
	config.Rdb.Set(config.Ctx, codeKey, code, time.Minute*5)

	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "验证码发送成功",
		"data":    nil,
	})
}

func Register(r *gin.Context) {
	var req request.User
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    nil,
		})
		return
	}
	codeKey := req.Mobile
	NewCode, _ := config.Rdb.Get(config.Ctx, codeKey).Result()
	if req.SendCode != NewCode {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证码错误",
			"data":    nil,
		})
		return
	}
	user := model.User{
		Password: req.Password,
		Mobile:   req.Mobile,
	}
	if err := user.CreateUser(); err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "用户创建失败",
			"data":    nil,
		})
		return
	}

	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "注册成功",
		"data":    user.ID,
	})
}

func Login(r *gin.Context) {
	var req request.User
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    nil,
		})
		return
	}

	codeKey := req.Mobile
	NewCode, _ := config.Rdb.Get(config.Ctx, codeKey).Result()
	if req.SendCode != NewCode {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "验证码错误",
			"data":    nil,
		})
		return
	}

	user := model.User{}
	if user.Password != req.Password {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "密码错误",
			"data":    nil,
		})
		return
	}

	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    user.ID,
	})
}
